// components/base/qrcode/index.js
import drawQrcode from 'weapp-qrcode-canvas-2d';
import componentBehavior from '../../../behaviors/component';
import { COMPONENT_OPTIONS } from '../../../constants/common';

Component({
    behaviors: [componentBehavior],
    options: {
        ...COMPONENT_OPTIONS,
    },
    properties: {
        qrCodeId: {
            type: String,
            value: 'qrCodeId',
        },
        width: {
            type: Number,
            value: 200,
        },
        height: {
            type: Number,
            value: 200,
        },
        content: {
            type: String,
            value: '',
        },
    },
    observers: {
        'content': function(content) {
            content && this._handleRender();
        },
    },
    data: {
        tempFilePath: '',
    },
    methods: {
        _handleRender() {
            const _ = this;
            const query = this.createSelectorQuery()
            const { qrCodeId, width, height, content } = this.data;
            query.select(`#${qrCodeId}`).fields({
                node: true,
                size: true
            }).exec((res) => {
                var canvas = res[0].node;

                // 生成二维码
                drawQrcode({
                    canvas: canvas,
                    canvasId: qrCodeId,
                    width,
                    padding: 20,
                    text: content,
                    background: '#ffffff',
                    foreground: '#000000',
                });

                // 获取临时路径
                wx.canvasToTempFilePath({
                    canvas: canvas,
                    canvasId: qrCodeId,
                    width,
                    height,
                    destWidth: width,
                    destHeight: height,
                    x: 0,
                    y: 0,
                    success(res) {
                        const tempFilePath = res.tempFilePath;
                        _.setData({ tempFilePath })
                        _.triggerEvent('getQrcodeFile', tempFilePath);
                    },
                    fail(res) {
                        console.error(res)
                    },
                });
            });
        }
    }
})
